package sk.sigp.aobot.swinggui.utils;

import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.io.IOException;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;

import sk.sigp.aobot.Colors;
import sk.sigp.aobot.Connect;
import sk.sigp.aobot.Utils;
import sk.sigp.aobot.base.HaveListeners;
import sk.sigp.aobot.client.CrawlerHttpClient;

public class HyperTextListener 
	extends HaveListeners<NotifiableByHyperTextListener> implements HyperlinkListener {

	private CrawlerHttpClient html = new CrawlerHttpClient();
	
	private Connect connect;
	
	private NotifiableByHyperTextListener defaultListener;
	
	public void hyperlinkUpdate(HyperlinkEvent e) {
		if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
			String str = e.getDescription();
			String sn = "";
			String fetched = "";
			boolean page = false;
			if (str.startsWith("text://")) {
				sn = "text details";
				JFrame dx = new JFrame();
				str = str.replaceAll("CCInfoHeader", Utils
						.colorToRgb(Colors.FOREGROUND));
				str = str.replaceAll("CCInfoText", Utils
						.colorToRgb(Colors.FOREGROUND));
				String embed = "<html><head></head><body><font color="
						+ Utils.colorToRgb(Colors.FOREGROUND) + ">"
						+ str.substring(7) + "</font></body></html>";
				embed = embed.replaceAll("\n", "<br/>");
				embed = embed.trim();
				JPanel o = new JPanel();
				JPanel core = new JPanel();
				core.setLayout(new BorderLayout());
				final JEditorPane area = new JEditorPane();
				area.setEditable(false);
				area.setContentType("text/html");
				area.setText(embed);
				area.setBackground(Colors.BACKGROUND);
				area.setForeground(Colors.FOREGROUND);
				area.addHyperlinkListener(new HyperTextListener(getConnect(),getDefaultListener()));
				o.setLayout(new BorderLayout());
				JScrollPane pane = new JScrollPane(area);
				core.add(pane, BorderLayout.CENTER);
				dx.setContentPane(o);
				dx.setSize(500, 300);
				dx.setLocation((int) Toolkit.getDefaultToolkit()
						.getScreenSize().getWidth()
						/ 2 - dx.getWidth() / 2, (int) Toolkit
						.getDefaultToolkit().getScreenSize().getHeight()
						/ 2 - dx.getHeight() / 2);
				dx.getContentPane().add(core, BorderLayout.CENTER);
				dx.setVisible(true);
				dx.setTitle("Brave Oest's Relay Chat v" + Utils.VERSION
						+ " - Detail Window (" + sn + ")");
				SwingUtilities.invokeLater(new Runnable() {
					public void run() {
						area.scrollRectToVisible(new Rectangle(0, 0, 1, 1));
					}
				});
			} else if (str.startsWith("itemref://")
					|| str.startsWith("chatcmd:///start")) {
				String url = "";
				if (str.startsWith("itemref://")) {
					sn = "auno item info";
					String px = str.substring(10);
					String[] prt = px.split("/");
					url = "http://auno.org/ao/db.php?id=" + prt[0] + "&ql="
							+ prt[2];

					try {
						fetched = html.httpToStringStupid(url);
					} catch (Exception e1) {
						e1.printStackTrace();
					}

					// url = "http://aomainframe.info/showitem.asp?LowID=" +
					// prt[0] + "&HiID=" + prt[1] + "&QL=" + prt[2];
				} else {
					sn = "start html";
					try {
						page = true;
						url = str.substring(16).trim();
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}

				JFrame dx = new JFrame();
				String embed = "<html><head></head><body>" + str.substring(7)
						+ "</body></html>";
				embed = embed.replaceAll("\n", "<br/>");
				embed = embed.replaceAll("\\<img.*\\>", "");
				embed = embed.trim();
				JPanel o = new JPanel();
				JPanel core = new JPanel();
				core.setLayout(new BorderLayout());
				final JEditorPane area = new JEditorPane();
				area.setEditable(false);
				area.setContentType("text/html");
				area.setBackground(Colors.BACKGROUND);
				area.setForeground(Colors.FOREGROUND);
				if (page) {
					try {
						area.setPage(url);
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				} else {
					fetched = fetched.substring(fetched
							.indexOf("<!-- begin content -->"), fetched
							.indexOf("<!-- end content -->"));
					fetched = "<html><head></head><body><div style=\"color:"
							+ Utils.colorToRgb(Colors.FOREGROUND) + "\">"
							+ fetched + "</div>" + "</body></html>";
					fetched = fetched.replaceAll("<legend>", "");
					fetched = fetched.replaceAll("</legend>", "<br />");
					fetched = fetched.replaceAll("\\<img.*\\>", "");
					area.setText(fetched);
				}
				// area.addHyperlinkListener(new HyperTextListener());
				o.setLayout(new BorderLayout());
				JScrollPane pane = new JScrollPane(area);
				core.add(pane, BorderLayout.CENTER);
				dx.setContentPane(o);
				dx.setSize(500, 300);
				dx.setLocation((int) Toolkit.getDefaultToolkit()
						.getScreenSize().getWidth()
						/ 2 - dx.getWidth() / 2, (int) Toolkit
						.getDefaultToolkit().getScreenSize().getHeight()
						/ 2 - dx.getHeight() / 2);
				dx.getContentPane().add(core, BorderLayout.CENTER);
				dx.setVisible(true);
				dx.setTitle("Brave Oest's Relay Chat v" + Utils.VERSION
						+ " - Detail Window (" + sn + ")");
				SwingUtilities.invokeLater(new Runnable() {
					public void run() {
						area.scrollRectToVisible(new Rectangle(0, 0, 1, 1));
					}
				});

			} else if (str.startsWith("chatcmd:///tell")) {
				String px = str.substring(16);
				int wc = px.indexOf(" ");
				if (wc == -1)
					return;
				String to = px.substring(0, wc).trim();
				String what = px.substring(wc + 1, px.length()).trim();
				getConnect().getCore().sendMessageToUser(what, to);
			} else if (str.startsWith("cmdt")) {
				String px = str.substring(4);
				fireTellActivated(px);
//				text2.setText(px);
//				box.setSelected(false);
			} else if (str.startsWith("cmdg")) {
				String px = str.substring(4);
				fireGroupActivated(px);
//				text2.setText(px);
//				box.setSelected(true);
			} else {
				fireNotify("dont know hypertext commmand contained in hyperlink");
				// System.out.println(str);
			}
		}
	}
	
	protected void fireNotify(String message) {
		fireEvent("notifyByHyperTextListener", message);
	}
	
	protected void fireGroupActivated(String group) {
		fireEvent("groupActivated", group);
	}	
	
	protected void fireTellActivated(String tellToUser) {
		fireEvent("tellActivated", tellToUser);
	}
	
	public HyperTextListener(Connect connect, NotifiableByHyperTextListener defaultListener) {
		super();
		setConnect(connect);
		setDefaultListener(defaultListener);
	}

	public Connect getConnect() {
		return connect;
	}

	public void setConnect(Connect connect) {
		this.connect = connect;
	}

	public NotifiableByHyperTextListener getDefaultListener() {
		return defaultListener;
	}

	public void setDefaultListener(NotifiableByHyperTextListener defaultListener) {
		if (getListeners().size()<1)
			getListeners().add(defaultListener);
		this.defaultListener = defaultListener;
	}

}
